import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_test1/app/base/base_list/widgets/refresh_widget.dart';
import 'package:flutter_test1/extension/num_extension.dart';
import 'package:flutter_test1/extension/string_extension.dart';
import 'package:flutter_test1/extension/widget_extension.dart';
import 'package:flutter_test1/gen/assets.gen.dart';
import 'package:flutter_test1/helper/dialog/dialog_helper.dart';
import 'package:flutter_test1/home/qr_code_dialog/qr_code_dialog.dart';
import 'package:flutter_test1/model/account_model.dart';
import 'package:flutter_test1/utils/toast.dart';
import 'package:flutter_test1/widgets/app_bar/app_bar.dart';
import 'package:flutter_test1/widgets/app_button.dart';
import 'package:flutter_test1/widgets/search_bar.dart';
import 'package:flutter_test1/widgets/sort_up.dart';
import 'package:get/get.dart';

import 'home_logic.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final logic = Get.put(HomeLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: xAppBar(
        context,
        '首页',
      ),
      body: Column(
        children: [
          searchBar(),
          10.h.extHeightBox,
          genAction(),
          5.h.extHeightBox,
          Obx(() =>
              '当前个数:${logic.inSearch.value ? logic.searchRes.length : logic.accounts.length}'
                  .extText()),
          sort(),
          contentList().extExpanded(),
        ],
      ).marginSymmetric(horizontal: 15.w),
    );
  }

  @override
  void dispose() {
    Get.delete<HomeLogic>();
    super.dispose();
  }

  Widget genAction() {
    return Obx(() {
      return logic.running.value
          ? GestureDetector(
              onTap: () => logic.stopGen(),
              child: Row(
                children: [
                  SizedBox(
                    width: 20.r,
                    height: 20.r,
                    child: CircularProgressIndicator(),
                  ),
                  10.w.extWidthBox,
                  '停止产生账号'.extText()
                ],
              ),
            )
          : GestureDetector(
              onTap: () => logic.genAccounts(),
              child: Row(
                children: [
                  Icon(
                    Icons.play_arrow_rounded,
                    size: 25.r,
                    color: Colors.blueAccent,
                  ),
                  '产生账号'.extText()
                ],
              ),
            );
    });
  }

  Widget contentList() {
    return Obx(() {
      return logic.inSearch.value ? searchList() : accountList();
    });
  }

  Widget searchBar() {
    return AppSearchBar(
      controller: logic.searchCtrl,
      onSearch: () => logic.onSearchTap(),
    );
  }

  Widget sort() {
    return Obx(() {
      List<String> tabs = [
        logic.ethUp.value ? 'eth升序' : 'eth降序',
        logic.tronUp.value ? 'tron升序' : 'tron降序',
      ];
      return Container(
        child: Row(
          children: List.generate(tabs.length, (i) {
            return Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Checkbox(
                  value: logic.sortIndex.value == i,
                  onChanged: (value) {
                    logic.sortIndex.value = i;
                    logic.loadData();
                  },
                ),
                GestureDetector(
                  onTap: () {
                    if (i == 0) {
                      logic.ethUp.value = !logic.ethUp.value;
                    } else {
                      logic.tronUp.value = !logic.tronUp.value;
                    }
                    logic.loadData();
                  },
                  child: SortUp(
                    title: tabs[i],
                    type: i == 0
                        ? (logic.ethUp.value ? 1 : 0)
                        : (logic.tronUp.value ? 1 : 0),
                  ),
                )
              ],
            );
          }),
        ),
      );
    });
  }

  Widget accountList() {
    return Obx(() {
      return logic.accounts.isNotEmpty
          ? RefreshWidget(
              controller: logic.refreshController,
              onRefresh: logic.onRefresh,
              child: ListView.separated(
                // padding: EdgeInsets.symmetric(horizontal: 15.w),
                shrinkWrap: true,
                itemBuilder: (c, i) => accountCard(i, logic.accounts[i]),
                separatorBuilder: (c, i) => 15.h.extHeightBox,
                itemCount: logic.accounts.length,
              ),
            )
          : refreshBtn();
    });
  }

  Widget searchList() {
    return Obx(() {
      return logic.searchRes.isNotEmpty
          ? RefreshWidget(
              controller: logic.refreshController,
              onRefresh: logic.onRefresh,
              child: ListView.separated(
                // padding: EdgeInsets.symmetric(horizontal: 15.w),
                shrinkWrap: true,
                itemBuilder: (c, i) => accountCard(i, logic.searchRes[i]),
                separatorBuilder: (c, i) => 15.h.extHeightBox,
                itemCount: logic.searchRes.length,
              ),
            )
          : refreshBtn();
    });
  }

  Widget refreshBtn() {
    return Center(
      child: AppButton(
        width: 80.w,
        height: 40.h,
        onPressed: () {
          logic.loadData();
        },
        content: '刷新',
      ),
    );
  }

  Widget accountCard(int index, AccountModel model) {
    Map<String, dynamic> modelMap = model.toJson();
    return Container(
        color: Colors.grey.withOpacity(0.2),
        padding: EdgeInsets.all(15.r),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListView.separated(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (c, i) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        modelMap.keys.toList()[i].toString().extText(
                            fontSize: 16.sp, fontWeight: FontWeight.bold),
                        if (modelMap.keys.toList()[i].toString() ==
                                'private_key' ||
                            modelMap.keys.toList()[i].toString() ==
                                'public_key' ||
                            modelMap.keys.toList()[i].toString() ==
                                'ethereum_address' ||
                            modelMap.keys.toList()[i].toString() ==
                                'tron_address')
                          IconButton(
                            onPressed: () {
                              DialogHelper.showCenterDialog(
                                width: 200.w,
                                QrCodeDialog(
                                  privateKey:
                                      modelMap.values.toList()[i].toString(),
                                ),
                              );
                            },
                            icon: Assets.images.qrCode.image(
                              width: 20.r,
                              height: 20.r,
                            ),
                          )
                      ],
                    ),
                    modelMap.values.toList()[i].toString().extText(),
                  ],
                );
              },
              separatorBuilder: (BuildContext context, int index) {
                return Container(
                  margin: EdgeInsets.symmetric(vertical: 10.h),
                  height: 1.h,
                  color: Colors.grey.withOpacity(0.2),
                );
              },
              itemCount: modelMap.keys.length,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                'index: ${index + 1}'.extText(),
                Spacer(),
                IconButton(
                  onPressed: () {
                    Clipboard.setData(ClipboardData(text: modelMap.toString()));
                    Toast.show('已复制到剪贴板');
                  },
                  icon: Assets.images.iconCopy.image(
                    width: 20.r,
                    height: 20.r,
                  ),
                ),
                IconButton(
                  onPressed: () {
                    logic.deleteAccount(model.privateKey!);
                  },
                  icon: Icon(
                    Icons.delete_forever_outlined,
                    size: 25.r,
                    color: Colors.red,
                  ),
                )
              ],
            )
          ],
        ));
  }
}
